package com.example.homework

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.homework.db.UserDBHelper
import com.example.homework.utils.Prefs
import com.example.homework.utils.RankUtils

class LoginActivity : AppCompatActivity() {

    private lateinit var etAccount:  EditText
    private lateinit var etUsername: EditText
    private lateinit var ivAvatar: ImageView
    private var avatarUri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        etAccount  = findViewById(R.id.et_account)
        etUsername = findViewById(R.id.et_username)
        ivAvatar   = findViewById(R.id.iv_avatar)
        val btnEnter = findViewById<Button>(R.id.btn_enter)

        ivAvatar.setOnClickListener { pickImage() }
        btnEnter.setOnClickListener { doLogin() }
    }

    /* 选择头像 */
    private fun pickImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*" }
        startActivityForResult(intent, 100)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            avatarUri = data?.data
            ivAvatar.setImageURI(avatarUri)
        }
    }

    private fun doLogin() {
        val account = etAccount.text.toString().trim()
        val username = etUsername.text.toString().trim()
        if (account.isEmpty() || username.isEmpty()) {
            Toast.makeText(this, "账号和昵称不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        val avatar = avatarUri?.toString() ?: ""

        val db = UserDBHelper(this)
        val user = db.loginOrRegister(account, username, avatar)
        db.close()

        // 记录最后一次登录账号
        Prefs.setLastAccount(this, account)

        // 更新服务器端用户信息
        val updated = RankUtils.updateUser(user, this)
        if (updated) {
            Toast.makeText(this, "用户信息已同步到服务器", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "用户信息同步失败，请检查网络", Toast.LENGTH_SHORT).show()
        }

        val intent = Intent(this, MainActivity::class.java).apply {
            putExtra("user", user)
        }
        startActivity(intent)
        finish()
    }
}